<template>
  <el-button type="primary" @click="openCateDialog()">添加</el-button>
  <el-table :data="tableData" style="width: 100%" table-layout="fixed">
    <el-table-column prop="id" label="Id" />
    <el-table-column prop="title" label="分类名称" />
    <el-table-column label="分类图片">
      <template #default="scope">
        <el-image style="width: 100px; height: 80px" :src="scope.row.img_path" />
      </template>
    </el-table-column>
    <el-table-column prop="sort" label="排序" />
    <el-table-column label="操作">
      <template #default="scope">
        <el-button type="primary" text @click="handleEdit(scope.row)"> 编辑 </el-button>
        <el-button type="danger" text @click="handleDelete(scope.row)"> 删除 </el-button>
      </template>
    </el-table-column>
  </el-table>
  <AddOrChangeCateDialog :cateDialogVisible="cateDialogVisible" :editCateData="editCateData"
    :closeCateDialog="closeCateDialog" @submit-cate="handleSubmitCate"></AddOrChangeCateDialog>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import AddOrChangeCateDialog from '../../components/AddOrChangeCateDialog.vue';
import instance from '../../utils/request';

const cateDialogVisible = ref(false)
const editCateData = ref(null)
const tableData = ref([]);
const getCateData = async () => {
  let res = await instance.get('Goods/goodsCategory')
  if (res.code == 200) {
    tableData.value = res.data
  }
}
onMounted(() => {
  getCateData()
})
// 打开添加分类对话框
const openCateDialog = () => {
  editCateData.value = null
  cateDialogVisible.value = true
}

// 编辑分类
const handleEdit = (row) => {
  editCateData.value = { ...row }
  cateDialogVisible.value = true
}

const closeCateDialog = () => {
  cateDialogVisible.value = false
  editCateData.value = null
}

// 处理分类提交（添加/编辑）
const handleSubmitCate = async (cateData) => {
  if (cateData.id) {
    // 编辑模式 - 更新现有分类
    const index = tableData.value.findIndex(item => item.id === cateData.id)
    if (index > -1) {
      tableData.value[index] = { ...cateData }
    }
  } else {
    // 新增模式 - 添加新分类
    const obj = {
      title: cateData.categoryName,
      img_path: cateData.categoryImage,
      sort: cateData.sortOrder
    }
    let res = await instance.post('goods/addCategory', obj)
    console.log(res);
    if (res.code == 200) {
      getCateData()
    }

  }
}

// 删除分类
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除分类 "${row.title}" 吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    // 删除操作
    let res = await instance.get(`Goods/deleteCategory?id=${row.id}`)
    if (res.code == 200) {
      ElMessage.success('删除成功')
    }
    getCateData()
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}
</script>

<style lang="scss" scoped></style>
